// 表示层
var express = require("express");
var router = express.Router();
let multiparty = require("multiparty");
let path = require("path");
const navsService = require("../service/navsService");

// 新增帖子
router.post("/", async function (req, res) {
    let { icon, name, createTime } = req.body;
    let data = await navsService.insert({
        icon, //图标链接
        name, // 名称
        createTime, // 创建时间
    });
    res.send(data);
});

// 查询（所有信息）
router.get("/all", async function (req, res) {
    let data = await navsService.findAll();
    console.log("data", data);
    res.send(data);
});

// 删除帖子
router.delete("/:id", async function (req, res) {
    let { id } = req.params;
    let data = await navsService.delete(id);
    res.send(data);
});

// 查询帖子
router.get("/", async function (req, res) {
    let { type, value, current, pageSize } = req.query;
    let searchParams = {};
    searchParams[type] = new RegExp(value);
    let data = await navsService.find(
        {
            current: current || 1,
            pageSize: pageSize,
        },
        searchParams
    );
    res.send(data);
});

// 根据id查询帖子
router.get("/:id", async function (req, res) {
    let { id } = req.params;
    let data = await navsService.findById(id);
    res.send(data);
});

// 修改帖子
router.put("/:id", async function (req, res) {
    let { id } = req.params;

    let { icon, name, createTime } = req.body;
    let data = await navsService.update({
        _id: id,
        icon,
        name,
        createTime
    });
    res.send(data);
});

router.post("/upload", function (req, res) {
    let imgPath = path.join(__dirname, "../public/images");
    // console.log("=======",__dirname);
    console.log("img",imgPath);
  
    var form = new multiparty.Form({ uploadDir: imgPath });
    form.parse(req, function (err, fields, files) {
      /*
          console.log(fields.username[0])
          console.log(fields.password[0])
  
          Object.keys(fields).forEach(function(name) {
              console.log('got field named ' + name + "--" + fields[name] + "----" + typeof fields[name]);
          });
  
          Object.keys(files).forEach(function(name) {
              console.log(files[name]);
          });
      */
  
      if (err) {
        res.send({ code: 1, msg: "上传失败", data: err });
      } else {
        var p = files.file[0].path.substring(
          files.file[0].path.indexOf("images")
        );
        console.log(p);
        res.send({ code: 0, msg: "上传成功", data: path.basename(p) });
      }
    });
  });


module.exports = router;
